package kryptologieBlatt1;
import java.awt.Graphics;

import javax.swing.JPanel;


public class VigenereDrawPanel extends JPanel{
	
	private int offsetX;
	private int offsetY;
	private int frameX;
	private int frameY;
	private int axisX;
	private int axisY;
	private double axisLength;
	private int chiffreLength;
	private LetterPair[] drawValues;
	private int strideX;
	private int strideY;
	
	
	public VigenereDrawPanel(LetterPair[] drawValues, int frameX, int frameY) {
		initVariables(drawValues, frameX, frameY);
	}
	
	private void initVariables(LetterPair[] drawValues, int frameX, int frameY){
		this.drawValues = drawValues;
		this.chiffreLength = chiffreLength;
		this.frameX = frameX;
		this.frameY = frameY;
		this.axisLength = 0.9;
		this.axisX = (int) (frameX * axisLength);
		this.axisY = (int) (frameY * axisLength);
		this.offsetX = (frameX - axisX) / 2;
		this.offsetY = (frameY - axisY) / 2;
		calcChiffreLength();
	}

	private void calcChiffreLength() {
		int length = 26;
		for (int i = 0; i < length; i++) {
			chiffreLength += drawValues[i].getFrequency();
		}
	}

	public void paint(Graphics g) {
		drawAxis(g);
		drawValues(g);
	}
	
	private void drawValues(Graphics g) {
		int length = drawValues.length;
		int x = 0;
		int y = 0;
		double temp = (double) drawValues[0].getFrequency() / chiffreLength;
		int valBefore = (int) (temp * 100);
		int valNow = 0;
		for (int i = 1; i < length; i++) {
			temp = (double) drawValues[i].getFrequency() / chiffreLength;
			valNow = (int) (temp * 100);
			x = offsetX + i * strideX;
			y = strideY;
			g.drawLine(x, (int) axisY + offsetY - (y * valBefore), x + strideX, (int) axisY + offsetY - (y * valNow));
			valBefore = valNow;
		}
	}



	private void drawAxis(Graphics g){
		double maxFreq = (double) drawValues[0].getFrequency() / chiffreLength;
		int maxY = (int) (maxFreq * 100);
		int maxX = 26;
		strideY = axisY / maxY;
		strideX = axisX / maxX;
		//X-Achse
		g.drawLine(offsetX, offsetY + axisY, offsetX + axisX, offsetY + axisY);
		//Y-Achse
		g.drawLine(offsetX, offsetY + axisY, offsetX, offsetY);
		
		int y = 0;
		int x = 0;
		
		//Y - Achsenbeschriftung
		for (int i = 1; i <= maxY; i++) {
			y = (offsetY + axisY) - i * strideY;
			g.drawLine(offsetX - 5, y, offsetX + 5, y);
			g.drawString(i + "%", 0, y);
		}
		
		y = offsetY + axisY;
		//X - Achsenbeschriftung
		for (int i = 1; i <= maxX; i++) {
			x = offsetX + (i * strideX);
			g.drawLine(x, y - 5, x, y + 5);
			g.drawString(drawValues[i - 1].getLetter(), (i+1) * strideX + 5, frameY);

		}
		
	}


}
